<template>
  <div id="fill-car-info" :class="{'pb-0': type === 'part'}">

    <!--<form-tips :tips="tips"></form-tips>-->

    <grey-header title="车辆信息" v-if="type === 'part'"></grey-header>

    <grey-header title="*车辆品牌型号注意大小写精确输入"></grey-header>

    <ul>
      <li class="public-form-li">
        <label class="long" for="carBrand">车辆品牌型号</label>
        <input
          type="text"
          id="carBrand"
          placeholder="请参照行驶证或车系"
          name="车辆品牌型号"
          v-model="formOne.carBrand"
          v-validate="'required'"
          :disabled="allDisabled">
        <span v-show="VeeErrors.has('车辆品牌型号')">{{ VeeErrors.first('车辆品牌型号') }}</span>
      </li>
      <li class="public-form-li li-click">
        <label class="long" for="carType">交管车辆种类</label>
        <input
          type="button"
          id="carType"
          :value="formOne.aboutType.type"
          @click="openPicker('aboutType', 'typeShow')"
          :disabled="allDisabled">
        <button
          class="type-btn"
          @click="openPicker('aboutType', 'typeShow')"
          :disabled="allDisabled"></button>
      </li>
      <li class="public-form-li">
        <label class="long" for="carNum">车架号<span>(全部)</span></label>
        <input
          type="text"
          id="carNum"
          placeholder="请输入全部车架号"
          name="车架号"
          v-model="formOne.carNum"
          v-validate="'required|alpha_num|max:17|min:17'"
          :disabled="allDisabled">
        <span v-show="VeeErrors.has('车架号')">{{ VeeErrors.first('车架号') }}</span>
      </li>
      <li class="public-form-li">
        <label class="long" for="carEngineNum">发动机号<span>(全部)</span></label>
        <input
          type="text"
          id="carEngineNum"
          placeholder="请输入全部发动机型号"
          name="发动机号"
          v-model="formOne.carEngineNum"
          v-validate="'required'"
          :disabled="allDisabled">
        <span v-show="VeeErrors.has('发动机号')">{{ VeeErrors.first('发动机号') }}</span>
      </li>
      <li class="public-form-li li-click">
        <label class="long" for="carEffectDate">{{ formOne.aboutEffectDate.dateType }}</label>
        <input
          type="button"
          id="carEffectDate"
          :value="carEffectDate"
          @click="openDatetimePicker('effectDatetimePicker')"
          :disabled="allDisabled">
        <button
          @click="openDatetimePicker('effectDatetimePicker')"
          :disabled="allDisabled"
          class="date-btn"></button>
      </li>
      <li class="public-form-li">
        <label class="long">车辆性质</label>
        <label for="homeUse">非营运
          <input
            type="radio"
            name="usage"
            id="homeUse"
            value="1"
            :disabled="allDisabled"
            v-model="formOne.usage">
        </label>
        <label for="business">营运
          <input
            type="radio"
            name="usage"
            id="business"
            value="2"
            :disabled="allDisabled"
            v-model="formOne.usage">
        </label>
      </li>
      <li class="public-form-li">
        <label class="long">外地车</label>
        <label for="local">是
          <input
            type="radio"
            name="locale"
            id="local"
            value="2"
            :disabled="allDisabled"
            v-model="formOne.locale">
        </label>
        <label for="outside">否
          <input
            type="radio"
            name="locale"
            id="outside"
            value="1"
            :disabled="allDisabled"
            v-model="formOne.locale">
        </label>
      </li>
      <li class="public-form-li">
        <label class="long">是否过户</label>
        <label for="secondHand">过户车
          <input
            type="radio"
            name="newly"
            id="secondHand"
            value="2"
            :disabled="allDisabled"
            v-model="formOne.newly">
        </label>
        <label for="allNew">非过户车
          <input
            type="radio"
            name="newly"
            id="allNew"
            value="1"
            :disabled="allDisabled"
            v-model="formOne.newly">
        </label>
      </li>
      <template v-if="formOne.newly === '2'">
        <li class="public-form-li li-click">
          <label class="long" for="carTransferDate">{{ formOne.aboutTransferDate.dateType }}</label>
          <input
            type="button"
            id="carTransferDate"
            :value="carTransferDate"
            @click="openDatetimePicker('transferDatetimePicker')"
            :disabled="allDisabled">
          <button
            @click="openDatetimePicker('transferDatetimePicker')"
            :disabled="allDisabled"
            class="date-btn"></button>
        </li>
      </template>
      <li class="public-form-li">
        <label class="long">是否按揭</label>
        <label for="mortgage">是
          <input
            type="radio"
            name="mortgage"
            id="mortgage"
            value="1"
            :disabled="allDisabled"
            v-model="formOne.mortgage">
        </label>
        <label for="notMortgage">否
          <input
            type="radio"
            name="mortgage"
            id="notMortgage"
            value="2"
            :disabled="allDisabled"
            v-model="formOne.mortgage">
        </label>
      </li>
      <template v-if="formOne.mortgage === '1'">
        <li class="public-form-li">
          <label class="long" for="beneficiary">受益人</label>
          <input
            type="text"
            id="beneficiary"
            placeholder="请输入受益人"
            name="受益人"
            v-model="formOne.beneficiary"
            v-validate="'required|userName'"
            :disabled="allDisabled">
          <span v-show="VeeErrors.has('受益人')">{{ VeeErrors.first('受益人') }}</span>
        </li>
        <li class="public-form-li">
          <label class="long" for="benefitProportion">受益比例(%)</label>
          <input
            type="text"
            id="benefitProportion"
            placeholder="请输入受益百分比"
            name="受益比例"
            v-model="formOne.benefitProportion"
            v-validate="'required|decimal:1|min_value:1|max_value:100'"
            :disabled="allDisabled">
          <span v-show="VeeErrors.has('受益比例')">{{ VeeErrors.first('受益比例') }}</span>
        </li>
        <li class="public-form-li li-textarea">
          <label class="long" for="specially">特别约定</label>
          <textarea
            name="特别约定"
            id="specially"
            :disabled="allDisabled"
            v-model="formOne.specially"
            v-validate="'required'"></textarea>
          <span v-show="VeeErrors.has('特别约定')">{{ VeeErrors.first('特别约定') }}</span>
        </li>
      </template>
      <li class="public-form-li li-click">
        <label class="long" for="taxesType">纳税类型</label>
        <input
          type="button"
          id="taxesType"
          :value="formOne.aboutTaxesType.taxesType"
          @click="openPicker('aboutTaxesType', 'taxesTypeShow')"
          :disabled="allDisabled">
        <button
          class="type-btn"
          @click="openPicker('aboutTaxesType', 'taxesTypeShow')"
          :disabled="allDisabled"></button>
      </li>
      <template v-if="this.formOne.aboutTaxesType.taxesTypeCode !== 1">
        <li class="public-form-li li-click">
          <label class="long" for="taxesReductionReason">减免原因</label>
          <input
            type="button"
            id="taxesReductionReason"
            :value="formOne.aboutTaxesReductionReason.taxesReductionReason"
            @click="openPicker('aboutTaxesReductionReason', 'taxesReductionReasonShow')"
            :disabled="allDisabled">
          <button
            class="type-btn"
            @click="openPicker('aboutTaxesReductionReason', 'taxesReductionReasonShow')"
            :disabled="allDisabled"></button>
        </li>
        <li class="public-form-li">
          <label class="long" for="taxesDepartment">纳税机关</label>
          <input
            type="text"
            id="taxesDepartment"
            placeholder="请填写纳税机关"
            name="纳税机关"
            v-model="formOne.taxesDepartment"
            v-validate="'required'"
            :disabled="allDisabled">
          <span v-show="VeeErrors.has('纳税机关')">{{ VeeErrors.first('纳税机关') }}</span>
        </li>
        <li class="public-form-li li-click">
          <label class="long" for="taxesReductionPlan">减免方案</label>
          <input
            type="button"
            id="taxesReductionPlan"
            :value="formOne.aboutTaxesReductionPlan.taxesReductionPlan"
            @click="openPicker('aboutTaxesReductionPlan', 'taxesReductionPlanShow')"
            :disabled="allDisabled">
          <button
            class="type-btn"
            @click="openPicker('aboutTaxesReductionPlan', 'taxesReductionPlanShow')"
            :disabled="allDisabled"></button>
        </li>

        <li key="金额减免"
            v-if="formOne.aboutTaxesReductionPlan.taxesReductionPlan === '金额减免'"
            class="public-form-li">
            <label class="long" for="taxesReduction">减免金额(元)</label>
            <input
              type="text"
              id="taxesReduction"
              placeholder="请填写减免金额"
              name="减免金额"
              v-model="formOne.taxesReduction"
              v-validate="'required|decimal'"
              :disabled="allDisabled">
            <span v-show="VeeErrors.has('减免金额')">{{ VeeErrors.first('减免金额') }}</span>
        </li>

        <li key="减免比例"
            v-else-if="formOne.aboutTaxesReductionPlan.taxesReductionPlan === '比例减免'"
            class="public-form-li">
          <label class="long" for="taxesReductionRate">减免比例(%)</label>
          <input
            type="text"
            id="taxesReductionRate"
            placeholder="请填写减免比例"
            name="减免比例"
            v-model="formOne.taxesReductionRate"
            v-validate="'required|numeric|min_value:1|max_value:100'"
            :disabled="allDisabled">
          <span v-show="VeeErrors.has('减免比例')">{{ VeeErrors.first('减免比例') }}</span>
        </li>

        <li class="public-form-li">
          <label class="long" for="taxesNo">税务凭证</label>
          <input
            type="text"
            id="taxesNo"
            placeholder="请填写税务凭证"
            name="税务凭证"
            v-model="formOne.taxesNo"
            v-validate="'required'"
            :disabled="allDisabled">
          <span v-show="VeeErrors.has('税务凭证')">{{ VeeErrors.first('税务凭证') }}</span>
        </li>
      </template>
      <li class="public-form-li li-click">
        <label class="long" for="energy">能源种类</label>
        <input
          type="button"
          id="energy"
          :value="formOne.aboutEnergy.energy"
          @click="openPicker('aboutEnergy', 'energyShow')"
          :disabled="allDisabled">
        <button
          class="type-btn"
          @click="openPicker('aboutEnergy', 'energyShow')"
          :disabled="allDisabled"></button>
      </li>
    </ul>

    <grey-header title="投标/被保人信息"></grey-header>

    <ul>
      <li class="public-form-li li-single-checkbox">
        <label class="min">被保人</label>
        <label for="recognizeeSameAsOwner">同车主
          <input
            type="checkbox"
            id="recognizeeSameAsOwner"
            true-value="1"
            false-value="2"
            :disabled="allDisabled"
            v-model="formTwo.recognizeeSameAsOwner">
        </label>
      </li>
      <template v-if="formTwo.recognizeeSameAsOwner === '2'">
        <li class="public-form-li">
          <label class="long" for="recognizee">被保人姓名</label>
          <input
            type="text"
            id="recognizee"
            name="被保人姓名"
            v-model="formTwo.recognizee"
            v-validate="'required|userName'"
            :disabled="allDisabled">
          <span v-show="VeeErrors.has('被保人姓名')">{{ VeeErrors.first('被保人姓名') }}</span>
        </li>
        <li class="public-form-li">
          <label class="long" for="recognizeeIdNum">{{ formTwo.recognizeeIdNumLabel }}</label>
          <input
            type="text"
            id="recognizeeIdNum"
            name="被保人身份证号"
            v-model="formTwo.recognizeeIdNum"
            v-validate="'required|idNum'"
            :disabled="allDisabled">
          <span v-show="VeeErrors.has('被保人身份证号')">{{ VeeErrors.first('被保人身份证号') }}</span>
        </li>
        <li class="public-form-li">
          <label class="long" for="recognizeeTel">联系电话</label>
          <input
            type="tel"
            id="recognizeeTel"
            name="被保人联系电话"
            v-model="formTwo.recognizeeTel"
            v-validate="'required|tel'"
            :disabled="allDisabled">
          <span v-show="VeeErrors.has('被保人联系电话')">{{ VeeErrors.first('被保人联系电话') }}</span>
        </li>
      </template>
      <li class="public-form-li li-four-labels">
        <label class="min">投保人</label>
        <label for="applicantSameAsRecognizee">同被保人
          <input
            type="radio"
            name="applicantInfo"
            id="applicantSameAsRecognizee"
            value="1"
            :disabled="allDisabled"
            v-model="formTwo.applicant">
        </label>
        <label for="applicantSameAsOwner">同车主
          <input
            type="radio"
            name="applicantInfo"
            id="applicantSameAsOwner"
            value="2"
            :disabled="allDisabled"
            v-model="formTwo.applicant">
        </label>
        <label for="applicantSameAsOwner">自填
          <input
            type="radio"
            name="applicantInfo"
            id="applicantAnotherOne"
            value="0"
            :disabled="allDisabled"
            v-model="formTwo.applicant">
        </label>
      </li>
      <template v-if="formTwo.applicant === '0'">
        <li class="public-form-li">
          <label class="long" for="applicantName">投保人姓名</label>
          <input
            type="text"
            id="applicantName"
            name="投保人姓名"
            v-model="formTwo.applicantName"
            v-validate="'required|userName'"
            :disabled="allDisabled">
          <span v-show="VeeErrors.has('投保人姓名')">{{ VeeErrors.first('投保人姓名') }}</span>
        </li>
        <li class="public-form-li">
          <label class="long" for="applicantIdNum">{{ formTwo.applicantIdNumLabel }}</label>
          <input
            type="text"
            id="applicantIdNum"
            name="投保人身份证号"
            v-model="formTwo.applicantIdNum"
            v-validate="'required|idNum'"
            :disabled="allDisabled">
          <span v-show="VeeErrors.has('投保人身份证号')">{{ VeeErrors.first('投保人身份证号') }}</span>
        </li>
        <li class="public-form-li">
          <label class="long" for="applicantTel">联系电话</label>
          <input
            type="tel"
            id="applicantTel"
            name="投保人联系电话"
            v-model="formTwo.applicantTel"
            v-validate="'required|tel'"
            :disabled="allDisabled">
          <span v-show="VeeErrors.has('投保人联系电话')">{{ VeeErrors.first('投保人联系电话') }}</span>
        </li>
      </template>
      <li class="public-form-li message warn">
        注：被保险人信息默认为同车主信息，投保人信息默认为同保险人信息，如有不同请取消勾选并手动填写。
      </li>
    </ul>

    <grey-header title="上传照片"></grey-header>

    <ul>
      <li class="public-form-li li-single-checkbox" @click="togglePopup('carPicturesShow')">
        <label>验车照片</label>
        <label>
          <span>></span>
        </label>
      </li>
      <li class="public-form-li li-single-checkbox" @click="togglePopup('othersShow')">
        <label>其他说明</label>
        <label>
          <span>></span>
        </label>
      </li>
    </ul>

    <grey-header title="合格证与购车发票" v-if="type === 'part' && gotEvidenceOrNot"></grey-header>

    <article
      class="public-form-article"
      :class="{'pt-1': type === 'part', 'mt-0': type === 'part'}"
      v-if="gotEvidenceOrNot">
      <header v-if="type === 'page' && gotEvidenceOrNot">请上传合格证和购车发票</header>
      <section>
        <div class="item">
          <h2>合格证</h2>
          <div class="public-input-wrap" @click="$tool.clickIdDom('certificate')">
            <input
              type="file"
              id="certificate"
              name="certificate"
              @change="uploadPicture($event, 0, 'evidence')">
            <div v-if="!formThree.evidence[0].loading" class="cross">
              <span class="upright"></span>
              <span class="across"></span>
            </div>
            <spinner
              v-else-if="formThree.evidence[0].loading"
              class="spinner"
              type="snake"
              color="#0097ff"></spinner>
            <img
              v-if="formThree.evidence[0].img"
              :src="formThree.evidence[0].img"
              alt="">
          </div>
        </div>
        <div class="item">
          <h2>购车发票</h2>
          <div class="public-input-wrap" @click="$tool.clickIdDom('invoice')">
            <input
              type="file"
              id="invoice"
              name="invoice"
              @change="uploadPicture($event, 1, 'evidence')">
            <div v-if="!formThree.evidence[1].loading" class="cross">
              <span class="upright"></span>
              <span class="across"></span>
            </div>
            <spinner
              v-else-if="formThree.evidence[1].loading"
              class="spinner"
              type="snake"
              color="#0097ff"></spinner>
            <img
              v-if="formThree.evidence[1].img"
              :src="formThree.evidence[1].img"
              alt="">
          </div>
        </div>
      </section>
      <p v-if="type === 'page'">温馨提示：合格证和购车发票可在下单时再提交，但必须提交后才能下单</p>
    </article>

    <grey-header title="行驶证及其附本" v-if="type === 'part' && gotLicenceOrNot"></grey-header>

    <article
      class="public-form-article"
      :class="{'pt-1': type === 'part', 'mt-0': type === 'part'}"
      v-if="gotLicenceOrNot">
      <header v-if="type === 'page' && gotLicenceOrNot">请上传行驶证及附本</header>
      <section>
        <div class="item licence-front">
          <h2>行驶证(必填)</h2>
          <div class="public-input-wrap" @click="$tool.clickIdDom('licenceOne')">
            <input
              :disabled="$route.params.type === 'check'"
              type="file"
              id="licenceOne"
              name="licenceOne"
              @change="uploadPicture($event, 0, 'licence')">
            <div class="cross">
              <span class="upright"></span>
              <span class="across"></span>
            </div>
            <img
              v-if="formThree.licence[0].img"
              :src="formThree.licence[0].img"
              alt="">
          </div>
        </div>
        <div class="item">
          <h2>附本(必填)</h2>
          <div class="public-input-wrap" @click="$tool.clickIdDom('licenceTwo')">
            <input
              :disabled="$route.params.type === 'check'"
              type="file"
              id="licenceTwo"
              name="licenceTwo"
              @change="uploadPicture($event, 1, 'licence')">
            <div class="cross">
              <span class="upright"></span>
              <span class="across"></span>
            </div>
            <img
              v-if="formThree.licence[1].img"
              :src="formThree.licence[1].img"
              alt="">
          </div>
        </div>
        <div class="item">
          <h2>附本(选填)</h2>
          <div class="public-input-wrap" @click="$tool.clickIdDom('licenceThree')">
            <input
              :disabled="$route.params.type === 'check'"
              type="file"
              id="licenceThree"
              name="licenceThree"
              @change="uploadPicture($event, 2, 'licence')">
            <div class="cross">
              <span class="upright"></span>
              <span class="across"></span>
            </div>
            <img
              v-if="formThree.licence[2].img"
              :src="formThree.licence[2].img"
              alt="">
          </div>
        </div>
      </section>
      <p v-if="type === 'page'">温馨提示：行驶证照片可在下单时再提交，但必须提交后才能下单</p>
      <p>*建议上传1.5m，格式为jpg的照片</p>
    </article>

    <footer class="public-footer-btn-box" v-if="type === 'page'">
      <button
        v-if="gotLicenceOrNot"
        @click="ocrParseToText"
        :disabled="allDisabled"
        class="couple-button">OCR自动识别</button>
      <button
        @click="submit"
        :disabled="submitDisabled"
        :class="{'couple-button': gotLicenceOrNot, 'single-button': gotEvidenceOrNot}">提交</button>
    </footer>

    <popup
      v-model="formOne.aboutPlace.placeShow"
      position="bottom"
      class="placesPopup">
      <picker
        :slots="formOne.aboutPlace.places"
        value-key="name"
        @change="pickedPlaceChange"></picker>
    </popup>

    <popup
      v-model="formOne.aboutType.typeShow"
      position="bottom"
      class="typePopup">
      <picker
        :slots="formOne.aboutType.types"
        value-key="name"
        @change="pickedTypeChange"></picker>
    </popup>

    <popup
      v-model="formOne.aboutTaxesType.taxesTypeShow"
      position="bottom"
      class="typePopup">
      <picker
        :slots="formOne.aboutTaxesType.taxesTypes"
        value-key="name"
        @change="pickedTaxesTypeChange"></picker>
    </popup>

    <popup
      v-model="formOne.aboutTaxesReductionReason.taxesReductionReasonShow"
      position="bottom"
      class="typePopup">
      <picker
        :slots="formOne.aboutTaxesReductionReason.taxesReductionReasons"
        value-key="name"
        @change="pickedTaxesReductionReasonChange"></picker>
    </popup>

    <popup
      v-model="formOne.aboutTaxesReductionPlan.taxesReductionPlanShow"
      position="bottom"
      class="typePopup">
      <picker
        :slots="formOne.aboutTaxesReductionPlan.taxesReductionPlans"
        value-key="name"
        @change="pickedTaxesReductionPlanChange"></picker>
    </popup>

    <popup
      v-model="formOne.aboutEnergy.energyShow"
      position="bottom"
      class="typePopup">
      <picker
        :slots="formOne.aboutEnergy.energies"
        value-key="name"
        @change="pickedEnergyChange"></picker>
    </popup>

    <datetime-picker
      type="date"
      :startDate="formOne.aboutEffectDate.startDate"
      :endDate="formOne.aboutEffectDate.endDate"
      v-model="formOne.aboutEffectDate.date"
      @confirm="confirmEffectDate"
      @cancel="pickPopupChange(false)"
      ref="effectDatetimePicker">
    </datetime-picker>

    <datetime-picker
      type="date"
      :startDate="formOne.aboutTransferDate.startDate"
      :endDate="formOne.aboutTransferDate.endDate"
      v-model="formOne.aboutTransferDate.date"
      @confirm="confirmTransferDate"
      @cancel="pickPopupChange(false)"
      ref="transferDatetimePicker">
    </datetime-picker>

    <popup
      v-model="formThree.carPicturesShow"
      position="right"
      class="picturesPopup">
      <div class="wrap">
        <article>
          <div v-for="(item, index) in formThree.pictures" class="item">
            <h2>{{ item.title }}</h2>
            <div class="public-input-wrap" @click="$tool.clickIdDom(item.id)">
              <input
                type="file"
                :id="item.id"
                :name="item.id"
                @change="uploadPicture($event, index, 'pictures')"
                :disabled="allDisabled">
              <div class="cross" v-if="editable">
                <span class="upright"></span>
                <span class="across"></span>
              </div>
              <img
                v-if="item.img"
                :src="item.img"
                alt="">
            </div>
          </div>
        </article>
        <div class="public-btn-box">
          <button class="submit" @click="togglePopup('carPicturesShow')">返回</button>
        </div>
      </div>
    </popup>

    <popup
      v-model="formThree.othersShow"
      position="right"
      class="picturesPopup">
      <div class="wrap">
        <article>
          <div v-for="(item, index) in formThree.others" class="item">
            <h2></h2>
            <div class="public-input-wrap" @click="$tool.clickIdDom(item.id)">
              <input
                type="file"
                :id="item.id"
                :name="item.id"
                @change="uploadPicture($event, index, 'others')"
                :disabled="allDisabled">
              <div class="cross" v-if="editable">
                <span class="upright"></span>
                <span class="across"></span>
              </div>
              <img
                v-if="item.img"
                :src="item.img"
                alt="">
            </div>
          </div>
        </article>
        <div class="public-btn-box">
          <button class="submit" @click="togglePopup('othersShow')">返回</button>
        </div>
      </div>
    </popup>
  </div>
</template>

<script>
  import { DatetimePicker, Popup, Picker, Toast, Indicator, Spinner } from 'mint-ui';
  import GreyHeader from './grey-header.vue';
  import FormTips from './form-tips.vue';
  import { taxesTypes, taxesReductionReasons, taxesReductionPlans, taxesDepartments, energies } from '../../assets/scripts/_constant';
  export default {
    name: "fill-car-info",
    components: {
      DatetimePicker,
      Popup,
      Picker,
      GreyHeader,
      FormTips,
      Spinner
    },
    props: ['type', 'info', 'editable', 'gotLicence', 'gotEvidence'],
    data() {
      return {
        tips: '注：可使用OCR系统，拍摄行驶证照片，自动识别证件信息',
        formOne: {
          carBrand: '',
          aboutPlace: {
            placeShow: false,

            // 数据
            province: '',
            city: '',
            placeCode: '',

            // 城市汇总（一个省的所有城市为一个数组）

            citiesArr: [
              [
                {
                  name: '请选择',
                  id: ''
                }
              ]
            ],

            // picker数据格式

            places: [
              {
                flex: 1,
                values: [
                  {
                    name: '请选择',
                    index: 0
                  }
                ],
                textAlign: 'center'
              },
              {
                divider: true,
                content: '-'
              },
              {
                flex: 1,

                // 结构参考 citiesArr 的 item

                values: [
                  {
                    name: '请选择',
                    id: ''
                  }
                ],
                textAlign: 'center'
              }
            ]
          },
          aboutType: {
            typeShow: false,
            type: '',
            typeCode: '',
            types: [
              {
                flex: 1,
                values: [
                  {
                    name: '请选择交管车辆种类'
                  }
                ],
                textAlign: 'center'
              }
            ]
          },
          aboutTaxesType: {
            taxesTypeShow: false,
            taxesType: '',
            taxesTypeCode: '',
            taxesTypes: [
              {
                flex: 1,
                values: taxesTypes,
                textAlign: 'center',
                defaultIndex: 0
              }
            ]
          },
          aboutTaxesReductionReason: {
            taxesReductionReasonShow: false,
            taxesReductionReason: '',
            taxesReductionReasonCode: '',
            taxesReductionReasons: [
              {
                flex: 1,
                values: taxesReductionReasons,
                textAlign: 'center',
                defaultIndex: 0
              }
            ]
          },
          aboutTaxesReductionPlan: {
            taxesReductionPlanShow: false,
            taxesReductionPlan: '',
            taxesReductionPlanCode: '',
            taxesReductionPlans: [
              {
                flex: 1,
                values: taxesReductionPlans,
                textAlign: 'center',
                defaultIndex: 0
              }
            ]
          },
          taxesReductionReasonCodeLong: '',
          taxesDepartment: '',
          taxesReduction: '',
          taxesReductionRate: '',
          taxesNo: '',
          aboutEnergy: {
            energyShow: false,
            energy: '',
            energyCode: '',
            energies: [
              {
                flex: 1,
                values: energies,
                textAlign: 'center',
                defaultIndex: 0
              }
            ]
          },
          carNum: '',
          carEngineNum: '',
          aboutEffectDate: {
            date: '',
            dateType: '登记日期',
            formattedYear: '' || '请选择',
            formattedMonth: '' || '请选择',
            formattedDay: '' || '请选择',
            startDate: new Date(new Date().getTime() - 20*365*24*3600*1000),
            endDate: new Date()
          },
          usage: '1',
          locale: '1',
          belong: '1',
          newly: '1',
          aboutTransferDate: {
            date: '',
            dateType: '过户日期',
            formattedYear: '' || '请选择',
            formattedMonth: '' || '请选择',
            formattedDay: '' || '请选择',
            startDate: new Date(new Date().getTime() - 20*365*24*3600*1000),
            endDate: new Date()
          },
          mortgage: '2',
          beneficiary: '',
          benefitProportion: '',
          specially: ''
        },
        formTwo: {
          recognizeeSameAsOwner: '1',
          recognizee: '',
          recognizeeIdNum: '',
          recognizeeIdNumLabel: '被保人身份证号',
          recognizeeTel: '',
          applicant: '1',
          applicantName: '',
          applicantIdNum: '',
          applicantIdNumLabel: '投保人身份证号',
          applicantTel: ''
        },
        formThree: {
          carPicturesShow: false,
          othersShow: false,
          pictures: [
            {
              title: '左前45度',
              id: 'leftFront',
              img: '',
              loading: false
            },
            {
              title: '右前45度',
              id: 'rightFront',
              img: '',
              loading: false
            },
            {
              title: '左后45度',
              id: 'leftBack',
              img: '',
              loading: false
            },
            {
              title: '右后45度',
              id: 'rightBack',
              img: '',
              loading: false
            },
            {
              title: '车架号照片',
              id: 'carNumImg',
              img: '',
              loading: false
            },
            {
              title: '仪表盘照片',
              id: 'panel',
              img: '',
              loading: false
            },
            {
              title: '其他',
              id: 'othersA',
              img: '',
              loading: false
            },
            {
              title: '其他',
              id: 'othersB',
              img: '',
              loading: false
            }
          ],
          others: [
            {
              id: 'other-1',
              img: '',
              loading: false
            },
            {
              id: 'other-2',
              img: '',
              loading: false
            },
            {
              id: 'other-3',
              img: '',
              loading: false
            },
            {
              id: 'other-4',
              img: '',
              loading: false
            },
            {
              id: 'other-5',
              img: '',
              loading: false
            },
            {
              id: 'other-6',
              img: '',
              loading: false
            },
            {
              id: 'other-7',
              img: '',
              loading: false
            },
            {
              id: 'other-8',
              img: '',
              loading: false
            }
          ],
          evidence: [
            {
              img: '',
              loading: false
            },
            {
              img: '',
              loading: false
            }
          ],
          licence: [
            {
              img: '',
              loading: false
            },
            {
              img: '',
              loading: false
            },
            {
              img: '',
              loading: false
            }
          ]
        },
        allDisabled: false,
        submitDisabled: false,
        gotEvidenceOrNot: false,
        gotLicenceOrNot: false
      }
    },
    computed: {
      carRegisterPlace: function () {
        return this.formOne.aboutPlace.province + ' - ' + this.formOne.aboutPlace.city;
      },
      carEffectDate: {
        get() {
          return this.formOne.aboutEffectDate.formattedYear + '-' + this.formOne.aboutEffectDate.formattedMonth + '-' + this.formOne.aboutEffectDate.formattedDay;
        },
        set(newValue) {

          // 格式：'2017-02-05'

          let strings = newValue.toString().split('-');
          this.formOne.aboutEffectDate.formattedYear = strings[0];
          this.formOne.aboutEffectDate.formattedMonth = strings[1];
          this.formOne.aboutEffectDate.formattedDay = strings[2];
        }
      },
      carTransferDate: {
        get() {
          return this.formOne.aboutTransferDate.formattedYear + '-' + this.formOne.aboutTransferDate.formattedMonth + '-' + this.formOne.aboutTransferDate.formattedDay;
        },
        set(newValue) {

          // 格式：'2017-02-05'

          let strings = newValue.toString().split('-');
          this.formOne.aboutTransferDate.formattedYear = strings[0];
          this.formOne.aboutTransferDate.formattedMonth = strings[1];
          this.formOne.aboutTransferDate.formattedDay = strings[2];
        }
      },
      carPicturesArr: function () {
        let arr = [];
        for (let i = 0; i < 8; i++) {
          arr.push(this.formThree.pictures[i].img);
        }
        return arr;
      },
      otherPicturesArr: function () {
        let arr = [];
        for (let i = 0; i < 8; i++) {
          arr.push(this.formThree.others[i].img);
        }
        return arr;
      }
    },
    methods: {
      pickPopupChange(newVal) {
        this.$tool.fixedTheBG(newVal, 'fill-car-info');
      },
      openDatetimePicker(picker) {
        this.$refs[picker].open();
        this.pickPopupChange(true);
        // tag
        setTimeout(() => {
          document.getElementsByClassName('v-modal')[0].onclick = function () {
            this.pickPopupChange(false);
          }.bind(this)
        }, 100)
      },
      openPicker(item, data) {
        this.formOne[item][data] = true;
      },
      pickedPlaceChange(picker, values) {

        // 根据省份获取城市列表

        picker.setSlotValues(1, this.formOne.aboutPlace.citiesArr[values[0].index]);

        // 赋值省份

        this.formOne.aboutPlace.province = values[0].name;

        // 数据结构是三个slot，但钩子回调里只能拿到有变化的那两个slot的实时value

        this.formOne.aboutPlace.placeCode = values[1].id;

        // 赋值城市

        this.formOne.aboutPlace.city = values[1].name;
      },
      pickedTypeChange(picker, values) {
        if (values[0]) {
          this.formOne.aboutType.typeCode = values[0].car_no;
          this.formOne.aboutType.type = values[0].name;
        }
      },
      pickedTaxesTypeChange(picker, values) {
        if (values[0]) {
          this.formOne.aboutTaxesType.taxesTypeCode = values[0].code;
          this.formOne.aboutTaxesType.taxesType = values[0].name;
        }
      },
      pickedTaxesReductionReasonChange(picker, values) {
        if (values[0]) {
          this.formOne.aboutTaxesReductionReason.taxesReductionReasonCode = values[0].code;
          this.formOne.aboutTaxesReductionReason.taxesReductionReason = values[0].name;
          this.formOne.taxesReductionReasonCodeLong = values[0].codeLong;
        }
      },
      pickedTaxesReductionPlanChange(picker, values) {
        if (values[0]) {
          this.formOne.aboutTaxesReductionPlan.taxesReductionPlanCode = values[0].code;
          this.formOne.aboutTaxesReductionPlan.taxesReductionPlan = values[0].name;
        }
      },
      pickedEnergyChange(picker, values) {
        if (values[0]) {
          this.formOne.aboutEnergy.energyCode = values[0].code;
          this.formOne.aboutEnergy.energy = values[0].name;
        }
      },
      confirmEffectDate(date) {
        this.formOne.aboutEffectDate.formattedYear = this.$tool.formattedDate(date).year;
        this.formOne.aboutEffectDate.formattedMonth = this.$tool.formattedDate(date).month;
        this.formOne.aboutEffectDate.formattedDay = this.$tool.formattedDate(date).day;

        this.pickPopupChange(false);
      },
      confirmTransferDate(date) {
        this.formOne.aboutTransferDate.formattedYear = this.$tool.formattedDate(date).year;
        this.formOne.aboutTransferDate.formattedMonth = this.$tool.formattedDate(date).month;
        this.formOne.aboutTransferDate.formattedDay = this.$tool.formattedDate(date).day;

        this.pickPopupChange(false);
      },
      togglePopup(type) {
        this.formThree[type] = !this.formThree[type];
      },
      uploadPicture(event, index, dataArr) {

        this.formThree[dataArr][index].loading = true;

        let formData = new FormData();
        formData.append('file', event.target.files[0]);
        this.$http.axios({
          url: this.$http.imgURL,
          method: 'post',
          data: formData
        }).then((res) => {

          this.formThree[dataArr][index].loading = false;

          if (res.data.error === 0) {
            this.formThree[dataArr][index].img = res.data.data.img_url;

            if (dataArr === 'evidence' || dataArr === 'licence') {
              this.$emit('updateCertification', res.data.data.img_url, dataArr, index);
            }
          } else if (res.data.error === 1) {
            alert(res.data.msg);
          }
        }).catch((error) => {
          this.formThree[dataArr][index].loading = false;
          console.log(error);
        })
      },
      submit() {
        this.$validator.validateAll().then((result) => {

          // 验证通过

          if (result) {
            this.$http.post({
              api: this.$api.INSURANCE_CAR_INFO,
              params: {
                car_owner_id: this.$route.params.id,

                /**
                 * 表单一
                 */
                model: (this.formOne.carBrand).replace('牌', ''),
                provice: this.formOne.aboutPlace.placeCode,
                traffic: this.formOne.aboutType.typeCode,
                vin: (this.formOne.carNum).toUpperCase(),
                engine_num: (this.formOne.carEngineNum).toUpperCase(),
                buy_time: this.carEffectDate,
                car_nature: this.formOne.usage,
                is_local: this.formOne.locale,
                nature: this.formOne.belong,
                transfer: this.formOne.newly,
                transfer_date: this.carTransferDate,
                mortgage: this.formOne.mortgage,
                beneficiary: this.formOne.beneficiary,
                scale: this.formOne.benefitProportion,
                special_agreement: this.formOne.specially,

                taxes_type: this.formOne.aboutTaxesType.taxesTypeCode,
                taxes_reason: this.formOne.aboutTaxesReductionReason.taxesReductionReasonCode,
                taxes_organ: this.formOne.taxesDepartment,
                taxes_code: this.formOne.taxesReductionReasonCodeLong,
                taxes_program: this.formOne.aboutTaxesReductionPlan.taxesReductionPlanCode,
                taxes_no: this.formOne.taxesNo,
                taxes_amount: this.formOne.taxesReduction,
                taxes_proportion: this.formOne.taxesReductionRate / 100 || 0,
                fuel_type: this.formOne.aboutEnergy.energyCode,

                /**
                 * 表单二
                 */
                insured: this.formTwo.recognizeeSameAsOwner,

                // 被保人信息（非必传）

                insured_name: this.formTwo.recognizeeSameAsOwner === '1' ? '' : this.formTwo.recognizee,
                insured_num: this.formTwo.recognizeeSameAsOwner === '1' ? '' : this.formTwo.recognizeeIdNum,
                insured_phone: this.formTwo.recognizeeSameAsOwner === '1' ? '' : this.formTwo.recognizeeTel,

                policy_holder: this.formTwo.applicant,

                // 投保人信息（非必传）

                policy_name: this.formTwo.applicantName,
                policy_num: this.formTwo.applicantIdNum,
                policy_phone: this.formTwo.applicantTel,

                /**
                 * 表单三
                 */

                car_url: this.carPicturesArr,
                remark: this.otherPicturesArr,
                certificate_url: this.formThree.evidence[0].img,
                invoice: this.formThree.evidence[1].img,

                // 有车牌时必传（修改）

                car_id: this.$route.params.car_id !== 'none' ? this.$route.params.car_id : '',
                driving_face: this.formThree.licence[0].img,
                driving_back: this.formThree.licence[1].img,
                invoice2: this.formThree.licence[2].img
              },
              success: (res) => {

                this.$tool.whenToast(
                  () => {

                    // 提示并禁止重复提交、点击，不再恢复（组件即将销毁）

                    this.submitDisabled = true;
                    this.allDisabled = true;
                  },
                  {
                    message: '提交成功，请继续填写保单信息',
                    className: 'public-long-toast',
                    duration: -1
                  },
                  () => {
                    this.$router.push({
                      name: 'FillInsurancePolicy',
                      params: {
                        type: this.$route.params.type,
                        car_owner_id: res.data.data.car_owner_id,
                        car_id: res.data.data.car_id
                      }
                    });
                  },2000
                );
              }
            });
          } else {

            this.$tool.whenToast(
              () => {

                // 禁止重复点击

                this.submitDisabled = true;
              },
              {
                message: '请完善车辆信息',
                duration: -1,
                iconClass: 'public-toast-icon error'
              },
              () => {

                // 恢复点击

                this.submitDisabled = false;
              },2000
            );
          }
        })
      },
      partInfoApply() {
        let info = this.info;

        this.formOne.carBrand = info.carBrand;
        // 所在地与交管类型放在 http success 中处理
        this.formOne.carNum = info.carNum;
        this.formOne.carEngineNum = info.carEngineNum;
        this.carEffectDate = info.date || '请选择-请选择-请选择';
        this.formOne.usage = info.usage || '1';
        this.formOne.locale = info.locale || '1';
        this.formOne.belong = info.belong || '1';
        this.formOne.newly = info.newly || '1';
        this.carTransferDate = info.carTransferDate || '请选择-请选择-请选择';
        this.formOne.mortgage = info.mortgage || '2';
        this.formOne.beneficiary = info.beneficiary;
        this.formOne.benefitProportion = info.benefitProportion;
        this.formOne.specially = info.specially;

        let _this = this;

        info.taxesTypeCode && taxesTypes.forEach(function (item, index) {
          if (item.code == info.taxesTypeCode) {
            return _this.formOne.aboutTaxesType.taxesTypes[0].defaultIndex = index;
          }
        });

        info.taxesReductionReasonCode && taxesReductionReasons.forEach(function (item, index) {
          if (item.code == info.taxesReductionReasonCode) {
            return _this.formOne.aboutTaxesReductionReason.taxesReductionReasons[0].defaultIndex = index;
          }
        });

        info.taxesReductionPlanCode && taxesReductionPlans.forEach(function (item, index) {
          if (item.code == info.taxesReductionPlanCode) {
            return _this.formOne.aboutTaxesReductionPlan.taxesReductionPlans[0].defaultIndex = index;
          }
        });

        this.formOne.taxesReductionRate = info.taxesReductionRate * 100;

        info.energyCode && energies.forEach(function (item, index) {
          if (item.code == info.energyCode) {
            return _this.formOne.aboutEnergy.energies[0].defaultIndex = index;
          }
        });

        this.formOne.taxesDepartment = info.taxesDepartment;
        this.formOne.taxesReductionReasonCodeLong = info.taxesReductionReasonCodeLong;
        this.formOne.taxesReduction = info.taxesReduction;
        this.formOne.taxesNo = info.taxesNo;

        this.formTwo.recognizeeSameAsOwner = info.recognizeeSameAsOwner || '1';
        this.formTwo.recognizee = info.recognizee;
        this.formTwo.recognizeeIdNum = info.recognizeeIdNum;
        this.formTwo.recognizeeTel = info.recognizeeTel;
        this.formTwo.applicant = info.applicant || '1';
        this.formTwo.applicantName = info.applicantName;
        this.formTwo.applicantIdNum = info.applicantIdNum;
        this.formTwo.applicantTel = info.applicantTel;

        for (let i = 0; i < 8; i++) {
          this.formThree.pictures[i].img = info.pictures[i];
          this.formThree.others[i].img = info.others[i];
        }

        this.formThree.evidence[0].img = info.evidence[0];
        this.formThree.evidence[1].img = info.evidence[1];

        this.formThree.licence[0].img = info.licence[0];
        this.formThree.licence[1].img = info.licence[1];
        this.formThree.licence[2].img = info.licence[2];
      },
      ocrParseToText() {
        if (!this.formThree.licence[0].img) {
          Toast('需要客户的行驶证正面')
        } else {

          // 提示

          Indicator.open({
            text: '分析中...',
            spinnerType: 'snake'
          });

          // 禁止其它点击

          this.allDisabled = true;
          this.submitDisabled = true;

          let licenceFormData = new FormData();
          licenceFormData.append('file', document.getElementById('licenceOne').files[0]);

          this.$http.axios({
            url: this.$http.ocrURL + '&type=3',
            method: 'post',
            data: licenceFormData
          }).then(res => {

            // 关闭提示

            Indicator.close();

            // 释放其他点击

            this.allDisabled = false;
            this.submitDisabled = false;

            if (res.data.error === 0) {
              Toast('行驶证识别成功');

              // 信息赋值

              let info = res.data.data.ocr_info,
                  types = this.formOne.aboutType.types[0].values,
                  date;

              this.formOne.carBrand = info.model;
              this.formOne.carEngineNum = info.engine_num;

              date = info.register_date.substr(0, 4) + '-'
                + info.register_date.substr(4, 2) + '-'
                + info.register_date.substr(6, 2);

              this.carEffectDate = date;
              this.formOne.usage = info.use_character === '非营运' ? '1' : '2';
              this.formOne.aboutType.type = info.vehicle_type;

              for (let i = 0; i < types.length; i++) {
                if (types[i].name === this.formOne.aboutType.type) {
                  this.formOne.aboutType.typeCode = types[i].car_no;
                  break;
                }

                // 无法匹配OCR返回的交管车辆类型字符串
                this.formOne.aboutType.type = '请选择';
              }

              this.formOne.carNum = info.vin;

            } else if (res.data.error === 1) {
              Toast('行驶证识别失败');
            }
          });
        }
      }
    },
    created() {

      // 城市代码

      this.$http.post({
        api: this.$api.INSURANCE_CITY,
        success: (res) => {

          let partOrNot = (this.type === 'part'),
            data = res.data.data;

          // 初始化时已有 0 项

          for (let index = 0; index < data.length; index++) {
            // 获取城市、汇总

            this.formOne.aboutPlace.citiesArr.push(data[index].cities);

            // 获取省份 并 直接赋值到picker数据结构中

            this.formOne.aboutPlace.places[0].values.push({
              name: data[index].name,
              index: index + 1
            });

            // 根据 cityCode 获取省市
            if (partOrNot && data[index].cities) {
              for (let subIndex = 0; subIndex < data[index].cities.length; subIndex++) {
                if (data[index].cities[subIndex].id === this.info.place) {
                  setTimeout(() => {
                    this.formOne.aboutPlace.province = data[index].name;
                    this.formOne.aboutPlace.city = data[index].cities[subIndex].name;
                    this.formOne.aboutPlace.placeCode = this.info.place;
                  }, 1000);
                  break;
                }
              }
            }
          }
        }
      });

      // 交管车辆种类

      this.$http.post({
        api: this.$api.INSURANCE_CAR_TYPE,
        success: (res) => {

          let data = res.data.data,
            partOrNot = (this.type === 'part');

          // 赋值

          data.unshift({
            // 据此判断是否已选择交管车辆种类
            car_no: '',
            name: '请选择交管车辆种类'
          });
          this.formOne.aboutType.types[0].values = data;

          if (partOrNot) {
            for (let i = 0; i < data.length; i++) {
              if (data[i].car_no === this.info.type) {
                setTimeout(() => {
                  this.formOne.aboutType.type = data[i].name;
                  this.formOne.aboutType.typeCode = this.info.type;
                }, 1000);
                break;
              }
            }
          }
        }
      });

      // 判断是否可编辑

      if (this.editable) {
        this.allDisabled = false;
      } else if (!this.editable) {
        this.allDisabled = true;
      }

      if (this.type === 'part') {
        this.partInfoApply();
      }

      // 判断是否有合格证发票

      if (this.$route.params.type === 'new') {
        this.gotEvidenceOrNot = true;
      } else if (this.$route.params.type === 'check' && (this.formThree.evidence[0].img || this.formThree.evidence[1].img)) {
        this.gotEvidenceOrNot = true;
      } else if (this.$route.name === 'MineOrderPending' && this.gotEvidence) {
        this.gotEvidenceOrNot = true;
      }

      // 判断是否有驾驶证

      if (this.$route.params.type === 'add' || this.$route.params.type === 'continue') {
        this.gotLicenceOrNot = true;
      } else if (this.$route.params.type === 'check' && (this.formThree.licence[0].img || this.formThree.licence[1].img)) {
        this.gotLicenceOrNot = true;
      } else if (this.$route.name === 'MineOrderPending' && this.gotLicence) {
        this.gotLicenceOrNot = true;
      }
    },
    watch: {
      'formOne.aboutPlace.placeShow': 'pickPopupChange',
      'formOne.aboutType.typeShow': 'pickPopupChange',
      'formOne.aboutTaxesType.taxesTypeShow': 'pickPopupChange',
      'formOne.aboutTaxesReductionReason.taxesReductionReasonShow': 'pickPopupChange',
      'formOne.aboutTaxesReductionPlan.taxesReductionPlanShow': 'pickPopupChange',
      'formOne.aboutEnergy.energyShow': 'pickPopupChange',
      'formThree.carPicturesShow': 'pickPopupChange',
      'formThree.othersShow': 'pickPopupChange'
    }
  }
</script>

<style lang="scss">

  #fill-car-info {

    $public-form-padding: 0 1rem;

    width: $size-as-parent;
    padding-bottom: $public-footer-btn-box-height;
    z-index: $content-z-index;

    >ul {
      padding: $public-form-padding;
      background: $white;
    }

    >.placesPopup, .typePopup {
      width: $size-as-parent;
      padding: 1rem 0;
    }

    >.picturesPopup {
      width: $size-as-parent;
      height: $size-as-parent;

      >.wrap {
        height: $size-as-parent;
        overflow-y: scroll;
        -webkit-overflow-scrolling: touch;

        >article {
          display: flex;
          justify-content: space-between;
          flex-wrap: wrap;
          padding: 1rem 1rem 0;
          background: $white;

          >.item {
            width: 48%;
            margin-bottom: 1.2rem;

            >h2 {
              font-size: 1.5rem;
              color: #333;
              text-align: center;
              margin-bottom: 1rem;
            }
          }
        }
      }
    }
  }
</style>
